
$(function () {

    // 初始化数据
    initData();

    // 引入数据校验
    initCheckdata();

    // 给是否发送邮件绑定单击事件
    $("input[name='isSendEmail']").click(function () {
        showOrHiddenEmail($(this).val());
    });

    // 保存按钮
    $(".press_btn1").click(function () {
        saveEventAndAlerts();
    })
    
    // 关闭窗口
    $(".press_btn2").click(function () {
        closeWindows();
    });

    $("#eventSort").change(function () {
        selectEventTypeBySort(this);
    });

    $("#eventOwner").change(function () {
        selectEmailByEventOwner();
    })
    // $("#eventTypeDiv").bind("click", ".add", function (e) {
    //     selectEventOwnerByType(e.target);
    // })

});

// function selectExistEvent(btn){
//     var flag;
//     var eventId = $(btn).val();
//     if (eventId == ""){
//         flag = false;
//         $("#eventSort").val("");
//         $("#eventDesc").val("");
//         $("#eventOwner").val("");
//         $("#eventType").val("");
//         // $("#eventLife").val("");
//         $("#threatLevel").val("");
//         $("#eventDeptId").val("");
//         $("input[name='isSendEmail']").each(function (i, n) {
//             if ($(this).val().trim() == 0) {
//                 $(this).attr("checked", "checked");
//             }
//         });
//         showOrHiddenEmail($("input[name='isSendEmail']:checked").val());
//         $("#emailToAddress").val("");
//         $("#emailTitle").val("");
//         $("#emailContent").val("");
//     }else if (eventId != ""){
//         $.ajax({
//             url:basePath + "/splunk/event/getEventById.do",
//             type:"post",
//             dataType:"json",
//             async:false,
//             data:{
//                 eventId:eventId
//             },
//             success:function (json) {
//                 var code = json.code;
//                 if (code == '200'){
//                     var event = json.data;
//                     eventVOJson = event;
//                     $("#eventSort").val(event.eventSort);
//                     $("#eventDesc").val(event.eventDesc);
//                     $("#eventOwner").val(event.eventOwner);
//                     $("#eventType").val(event.eventType);
//                     // $("#eventLife").val(json.invalidDays);
//                     $("#threatLevel").val(event.threatLevel);
//                     $("#eventDeptId").val(event.eventDeptId);
//                     $("input[name='isSendEmail']").each(function (i, n) {
//                         if ($(this).val().trim() == event.isSendEmail) {
//                             $(this).attr("checked", "checked");
//                         }
//                     });
//                     showOrHiddenEmail($("input[name='isSendEmail']:checked").val());
//                     $("#emailToAddress").val(event.emailToAddress);
//                     $("#emailTitle").val(event.emailTitle);
//                     $("#emailContent").val(event.emailContent);
//                     flag = true;
//                 }
//             }
//         });
//     }
//
//     // 设置为不可变
//     $("#eventSort").prop("disabled", flag);
//     $("#eventDesc").prop("disabled", flag);
//     $("#eventOwner").prop("disabled", flag);
//     $("#eventType").prop("disabled", flag);
//     // $("#eventLife").prop("disabled", flag);
//     $("#threatLevel").prop("disabled", flag);
//     $("#eventDeptId").prop("disabled", flag);
//     $("input[name='isSendEmail']").prop("disabled", flag);
//     $("#emailToAddress").prop("disabled", flag);
//     $("#emailTitle").prop("disabled", flag);
//     $("#emailContent").prop("disabled", flag);
// }


function initData() {
    // 将事件分类展示出来
    var div = '<option value="">请选择...</option>';
    $.each(all_event, function (eventSort, eventType) {
        div += '<option value="'+eventSort+'">'+eventSort+'</option>';
    });
    $("#eventSort").append(div);

    // 将事件处理专员展示出来
    var eventDiv = '<option value="">请选择...</option>';
    $.each(event_owner, function (owner, mail) {
        eventDiv += '<option value="' + owner + '">' + owner + '</option>';
    });
    $("#eventOwner").append(eventDiv);
    // 隐藏邮件模板
    showOrHiddenEmail($("input[name='isSendEmail']:checked").val());
}

function selectEmailByEventOwner() {
    $("#emailToAddress").html("");
    var eventOwner = $("#eventOwner").val();
    if (eventOwner != null && eventOwner != "") {
        $.each(event_owner, function (owner, mail) {
            if (eventOwner == owner) {
                $("#emailToAddress").append(mail);
            }
        })
    }
}

function selectEventTypeBySort(btn){
    $("#eventTypeDiv").html("");
    var div = '';
    var eventSort = $(btn).val().trim();
    if (eventSort != ''){
        $.each(all_event, function (sort, eventType) {
            if (eventSort == sort){
                //if (JSON.stringify(eventType) == "{}") {
                if (eventType.length == 0) {
                    div += '<input id="eventType" class="form-control add" checkData="NotNull" placeholder="请输入具体原因" />';
                }else {
                    div += '<select id="eventType" class="form-control add" checkData="NotNull">';
                    // $.each(eventType, function (type, mail) {
                    $.each(eventType, function (i, type) {
                        div += '<option value="' + type +'">' + type + '</option>';
                    });
                    div += '</select>';
                }
                $("#eventTypeDiv").append(div);
            }
        })
    }else if (eventSort == '') {
        div += '<select id="eventType" class="form-control add" checkData="NotNull">' +
                    '<option value="">请先选择事件分类...</option>' +
                '</select>';
        $("#eventTypeDiv").append(div);
    }
}

/**
 * 事件子类和事件处理专员暂无对应关系
 */
//function selectEventOwnerByType(btn) {
//     $("#eventOwnerDiv").html("");
//     var sort = $("#eventSort").val();
//     var type = $(btn).val();
//     if (type != null && type != '') {
//         $.each(all_event, function (eventSort, eventType) {
//             if (eventSort == sort) {
//                 $.each(eventType, function (type_1, owner) {
//                     if (type == type_1) {
//                         var div = "<input id='eventOwner' class='form-control' disabled='disabled' value='"+owner+"'/>";
//                         $("#eventOwnerDiv").append(div);
//                     }
//                 })
//             }
//         })
//     }else {
//         var div = "<input id='eventOwner' class='form-control' checkData='NotNull' placeholder='请输入事件owner' />";
//         $("#eventOwnerDiv").append(div);
//     }
// }

function showOrHiddenEmail(flag) {
    if (flag == 0) {
        $("#email_title").hide();
        $("#email_body").hide();
    }else if (flag == 1){
        $("#email_title").show();
        $("#email_body").show();
    }
}

function saveEventAndAlerts() {

    // 校验
    var flag = checkData();
    if(!flag){
        return flag;
    }

    // 事件
    var event = {};
    event.eventSort = $("#eventSort").val().trim();
    event.eventType = $("#eventType").val().trim();
    event.eventDesc = $("#eventDesc").val().trim();
    event.eventOwner = $("#eventOwner").val().trim();
    event.threatLevel = $("#threatLevel").val();
    event.eventDeptId = $("#eventDeptId").val();
    event.eventDeptName = $("#eventDeptId").find(":selected").text().trim();
    event.isSendEmail = $("input[name='isSendEmail']:checked").val();
    if (event.isSendEmail == 1) {
        var emailToAddress = $("#emailToAddress").val().trim();
        if (!checkEmail(emailToAddress)){
            return;
        }
        event.emailToAddress = emailToAddress;
        event.emailTitle = $("#emailTitle").val().trim();
        event.emailContent = $("#emailContent").val().trim();
    }
    // 告警相关
    //var alerts = alertListJson;
    //if(alerts!=''){
    //    alerts=JSON.stringify(alerts)
    //}
    /**
     * 修改为获取告警id
     */
    $.ajax({
        url: basePath + "/splunk/alert/saveEventAndAlerts.do",
        type: "post",
        dataType: "json",
        data: {
            eventStr: JSON.stringify(event),
            alertsStr:'',
            alertSids:alertListJson,
        },
        success:function (json) {
            var code = json.code;
            if (code == '200') {
                parent.layer.msg("事件已保存", {time: 1500}, function () {
                    closeWindows();
                    parent.alertSidArr = []; // 清空全局数组
                    parent.initData();
                });
            }else if (code == '500'){
                parent.layer.msg("事件保存失败", {time: 1500});
            }
        }
    });
    // 防止多次提交
    $(".press_btn1").addClass("disabled");
}

function closeWindows() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

function checkEmail(address) {
    var flag = true;
    var index = 0;
    var addressArr = address.split(",");
    addressArr.forEach(function (i, n) {
        if (index == 0) {
            var reg = /^[A-Za-z\d]+([\-_\.][A-Za-z\d]+)*@([A-Za-z\d]+[\-\.])+[A-Za-z\d]{2,5}$/;
            if(!reg.test($.trim(i))) {
                parent.layer.msg("收件人地址邮箱格式不正确", {time: 1500});
                index++;
                flag = false;
            }
        }
    });
    return flag;
}

